#include "widget_funce_control_industrial.h"
#include "ui_widget_funce_control_industrial.h"
#include <QUrl>
#include <QTime>
#include <QNetworkReply>
#include <QMessageBox>
#include <QSlider>
#include <QGraphicsDropShadowEffect>
#include <QRegExp>
#include <QTimer>

Widget_funcE_Control_industrial::Widget_funcE_Control_industrial(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget_funcE_Control_industrial),
    networkSession(nullptr),
    player(nullptr),
    networkManager(nullptr)
{
    ui->setupUi(this);
    // 设置网络配置
    QNetworkConfigurationManager manager;
    if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
        QNetworkConfiguration config = manager.defaultConfiguration();
        networkSession = new QNetworkSession(config, this);
        networkSession->open();

        connect(networkSession, &QNetworkSession::opened, this, [this](){
            player->setNetworkConfigurations(QList<QNetworkConfiguration>() << networkSession->configuration());
        });
    }

    // 初始化播放器
    player = new QMediaPlayer(this);
    networkManager = new QNetworkAccessManager(this);

    // 设置缓冲监控
    connect(player, &QMediaPlayer::bufferStatusChanged, this, [this](int percent){
        if(percent < 100 && player->state() == QMediaPlayer::PlayingState) {
            ui->lyricLabel->setText(QString("缓冲中...%1%").arg(percent));
            ui->lyricLabel->setStyleSheet(R"(
                QLabel#lyricLabel {
                    color: #FFD700;
                    font-size: 16px;
                    font-weight: bold;
                    background: rgba(224, 255, 255, 0.2);
                    border-radius: 10px;
                    padding: 15px;
                    min-height: 60px;
                    qproperty-alignment: AlignCenter;
                }
            )");
        }
    });

    // 设置窗口样式
    this->setStyleSheet(R"(
        QWidget {
            background-color: #f5f5f5;
            font-family: "Microsoft YaHei";
        }

        /* 主容器样式 */
        #Widget_funcE_Control_industrial {
            background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                          stop:0 #8E2DE2, stop:1 #4A00E0);
            border-radius: 15px;
            padding: 15px;
        }

        /* 按钮通用样式 */
        QPushButton {
            background-color: rgba(255, 255, 255, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 8px;
            color: black;
            padding: 8px 15px;
            min-width: 80px;
        }

        QPushButton:hover {   //鼠标悬停状态
            background-color: rgba(255, 255, 255, 0.3);
        }

        QPushButton:pressed {
            background-color: rgba(255, 255, 255, 0.1);
        }

        /* 播放控制按钮特殊样式 */
        #playButton, #pauseButton, #stopButton {
            min-width: 40px;
            max-width: 50px;
            border-radius: 20px;
            font-size: 15px;
        }

        /* 搜索框样式 */
        QLineEdit {
            background-color: rgba(250, 250, 210, 0.8);
            border: 1px solid rgba(0, 0, 0, 0.1);
            border-radius: 12px;
            padding: 5px 10px;
            font-size: 14px;
        }

        /* 下拉框样式 */
        QComboBox {
            background-color: rgba(255, 255, 255, 0.8);
            border: 1px solid rgba(0, 0, 0, 0.1);
            border-radius: 12px;
            padding: 5px 10px;
            min-width: 80px;
        }

        /* 歌曲列表样式 */
        QListWidget {
            background-color: rgba(255, 255, 255, 0.9);
            border: 1px solid rgba(0, 0, 0, 0.1);
            border-radius: 10px;
            padding: 5px;
            font-size: 14px;
        }

        QListWidget::item {
            padding: 8px 10px;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        }

        QListWidget::item:hover {
             background-color: rgba(74, 0, 224, 0.1);
        }

        QListWidget::item:selected {
        background-color: rgba(74, 0, 224, 0.2);
        color: #4A00E0;
        }

        /* 进度条样式 */
        QSlider::groove:horizontal {
            height: 6px;
            background: rgba(255, 255, 255, 0.3);
            border-radius: 3px;
        }

        QSlider::handle:horizontal {
            width: 14px;
            height: 14px;
            margin: -4px 0;
            background: white;
            border-radius: 7px;
        }

        QSlider::sub-page:horizontal {
            background: #4A00E0;
            border-radius: 3px;
        }

        /* 时间标签样式 */
        QLabel#currentTimeLabel, QLabel#totalTimeLabel {
            color: blue;
            font-size: 12px;
            min-width: 40px;
        }

        /* 当前歌曲标签 */
        QLabel#currentSongLabel {
            color: pink;
            font-size: 16px;
            font-weight: bold;
            qproperty-alignment: AlignCenter;
        }

        /* 歌词标签基础样式 */
        QLabel#lyricLabel {
            font-size: 16px;
            font-weight: bold;
            qproperty-alignment: AlignCenter;
            background: rgba(224, 255, 255, 0.2);
            border-radius: 10px;
            padding: 15px;
            min-height: 60px;
        }
    )");

    // 设置窗口属性
    this->setWindowTitle("音乐播放器");
    this->setWindowIcon(QIcon(":/音乐"));
    this->setMinimumSize(600, 500);

    // 进度条设置
    ui->progressSlider->setPageStep(1000);
    ui->progressSlider->setTracking(true);
    ui->progressSlider->setRange(0, 100);

    // 连接核心信号槽
    connect(player, &QMediaPlayer::positionChanged, this, &Widget_funcE_Control_industrial::updateProgress);
    connect(player, &QMediaPlayer::durationChanged, this, &Widget_funcE_Control_industrial::updateDuration);
    connect(player, &QMediaPlayer::stateChanged, this, &Widget_funcE_Control_industrial::handleSongFinished);
    connect(ui->searchEdit, &QLineEdit::returnPressed, ui->searchButton, &QPushButton::click);
    connect(player, &QMediaPlayer::positionChanged, this, &Widget_funcE_Control_industrial::displayCurrentLyric);
}

Widget_funcE_Control_industrial::~Widget_funcE_Control_industrial()
{
    delete ui;
    delete player;
    delete networkManager;
    delete networkSession;
}

// 播放/暂停/停止按钮槽函数
void Widget_funcE_Control_industrial::on_playButton_clicked() { player->play(); }
void Widget_funcE_Control_industrial::on_pauseButton_clicked() { player->pause(); }
void Widget_funcE_Control_industrial::on_stopButton_clicked() { player->stop(); }

// 进度条拖动处理
void Widget_funcE_Control_industrial::on_progressSlider_sliderMoved(int position)
{
    static qint64 lastPos = 0;
    if(qAbs(position - lastPos) > 1000) {
        player->setPosition(position);
        lastPos = position;
    }
}

// 媒体状态变化处理
void Widget_funcE_Control_industrial::handleSongFinished(QMediaPlayer::State state)
{
    if(state == QMediaPlayer::StoppedState) {
        ui->currentTimeLabel->setText("00:00");
        ui->progressSlider->setValue(0);
        ui->lyricLabel->setText("播放停止");
        ui->lyricLabel->setStyleSheet(R"(
            QLabel#lyricLabel {
                color: #FFFFFF;
                font-size: 16px;
                font-weight: bold;
                background: rgba(224, 255, 255, 0.2);
                border-radius: 10px;
                padding: 15px;
                min-height: 60px;
                qproperty-alignment: AlignCenter;
            }
        )");
    }
    else if(state == QMediaPlayer::PlayingState) {
        ui->lyricLabel->setText("正在播放...");
        ui->lyricLabel->setStyleSheet(R"(
            QLabel#lyricLabel {
                color: #FFFFFF;
                font-size: 16px;
                font-weight: bold;
                background: rgba(224, 255, 255, 0.2);
                border-radius: 10px;
                padding: 15px;
                min-height: 60px;
                qproperty-alignment: AlignCenter;
            }
        )");
    }
}

// 搜索按钮点击事件
void Widget_funcE_Control_industrial::on_searchButton_clicked()
{
    QString keyword = ui->searchEdit->text().trimmed();
    if(!keyword.isEmpty()) {
        ui->searchButton->setEnabled(false);
        ui->searchButton->setText("搜索中...");
        ui->songList->clear();

        QListWidgetItem *loadingItem = new QListWidgetItem("正在搜索...");
        loadingItem->setTextAlignment(Qt::AlignCenter);
        ui->songList->addItem(loadingItem);
        searchMusic(keyword);
    }
}

// 歌曲列表双击事件
void Widget_funcE_Control_industrial::on_songList_itemDoubleClicked(QListWidgetItem *item)
{
    QString id = item->data(Qt::UserRole).toString();
    QString type = item->data(Qt::UserRole+1).toString();

    if(type == "artist") {
        fetchArtistSongs(id);
    } else {
        playMusicById(id);
        fetchLyric(id);
    }
}

// 更新播放进度
void Widget_funcE_Control_industrial::updateProgress(qint64 position)
{
    if(!ui->progressSlider->isSliderDown()) {
        ui->progressSlider->setValue(position);
    }

    QTime currentTime(0, 0);
    currentTime = currentTime.addMSecs(position);
    QString format = currentTime.hour() > 0 ? "hh:mm:ss" : "mm:ss";
    ui->currentTimeLabel->setText(currentTime.toString(format));
}

// 更新总时长
void Widget_funcE_Control_industrial::updateDuration(qint64 duration)
{
    ui->progressSlider->setRange(0, duration);

    QTime totalTime(0, 0);
    totalTime = totalTime.addMSecs(duration);
    QString format = totalTime.hour() > 0 ? "hh:mm:ss" : "mm:ss";
    ui->totalTimeLabel->setText(totalTime.toString(format));
}

// 搜索音乐
void Widget_funcE_Control_industrial::searchMusic(const QString &keyword)
{
    int searchType = ui->searchTypeCombo->currentIndex();
    QString url;

    if(searchType == 0) {
        url = QString("http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=%1&type=1&offset=0&total=true&limit=10")
              .arg(keyword);
    } else {
        url = QString("http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=%1&type=100&offset=0&total=true&limit=10")
              .arg(keyword);
    }

    QNetworkRequest request;
    request.setUrl(QUrl(url));
    request.setRawHeader("Referer", "http://music.163.com/");
    request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");

    QNetworkReply *reply = networkManager->get(request);

    QTimer *timer = new QTimer(this);
    timer->setSingleShot(true);
    connect(timer, &QTimer::timeout, [reply]() {
        if(reply->isRunning()) reply->abort();
    });
    timer->start(10000);
    replyTimeouts.insert(reply, timer);

    connect(reply, &QNetworkReply::finished, [this, reply]() {
        if(replyTimeouts.contains(reply)) {
            replyTimeouts[reply]->deleteLater();
            replyTimeouts.remove(reply);
        }
        handleSearchReply(reply);
    });
}

// 播放指定ID的音乐
void Widget_funcE_Control_industrial::playMusicById(const QString &id)
{
    player->stop();
    lyricMap.clear();
    ui->lyricLabel->setText("准备播放...");
    ui->lyricLabel->setStyleSheet(R"(
        QLabel#lyricLabel {
            color: #FFFFFF;
            font-size: 16px;
            font-weight: bold;
            background: rgba(224, 255, 255, 0.2);
            border-radius: 10px;
            padding: 15px;
            min-height: 60px;
            qproperty-alignment: AlignCenter;
        }
    )");

    QString url = QString("http://music.163.com/song/media/outer/url?id=%1.mp3").arg(id);
    player->setMedia(QUrl(url));

    // 断开旧连接，避免信号重复
    disconnect(player, &QMediaPlayer::positionChanged, this, &Widget_funcE_Control_industrial::updateProgress);
    disconnect(player, &QMediaPlayer::durationChanged, this, &Widget_funcE_Control_industrial::updateDuration);
    disconnect(player, &QMediaPlayer::stateChanged, this, &Widget_funcE_Control_industrial::handleSongFinished);
    disconnect(player, &QMediaPlayer::bufferStatusChanged, this, nullptr);
    disconnect(player, QOverload<QMediaPlayer::Error>::of(&QMediaPlayer::error), this, nullptr);

    // 重新连接信号
    connect(player, &QMediaPlayer::positionChanged, this, &Widget_funcE_Control_industrial::updateProgress);
    connect(player, &QMediaPlayer::durationChanged, this, &Widget_funcE_Control_industrial::updateDuration);
    connect(player, &QMediaPlayer::stateChanged, this, &Widget_funcE_Control_industrial::handleSongFinished);
    connect(player, &QMediaPlayer::bufferStatusChanged, this, [this](int percent){
        if(percent < 100 && player->state() == QMediaPlayer::PlayingState) {
            ui->lyricLabel->setText(QString("缓冲中...%1%").arg(percent));
            ui->lyricLabel->setStyleSheet(R"(
                QLabel#lyricLabel {
                    color: #FFD700;
                    font-size: 16px;
                    font-weight: bold;
                    background: rgba(224, 255, 255, 0.2);
                    border-radius: 10px;
                    padding: 15px;
                    min-height: 60px;
                    qproperty-alignment: AlignCenter;
                }
            )");
        }
    });
    connect(player, QOverload<QMediaPlayer::Error>::of(&QMediaPlayer::error),
            [this](QMediaPlayer::Error error){
        ui->lyricLabel->setText("播放错误: " + player->errorString());
        ui->lyricLabel->setStyleSheet(R"(
            QLabel#lyricLabel {
                color: #FF4444;
                font-size: 16px;
                font-weight: bold;
                background: rgba(224, 255, 255, 0.2);
                border-radius: 10px;
                padding: 15px;
                min-height: 60px;
                qproperty-alignment: AlignCenter;
            }
        )");
    });

    fetchLyric(id);
    player->play();

    if(ui->songList->currentItem()) {
        ui->currentSongLabel->setText("正在播放: " + ui->songList->currentItem()->text());
    }
}

// 获取歌词
void Widget_funcE_Control_industrial::fetchLyric(const QString &id)
{
    QString url = QString("https://music.163.com/api/song/lyric?id=%1&lv=1&kv=1&tv=-1").arg(id);

    QNetworkRequest request;
    request.setUrl(QUrl(url));
    request.setRawHeader("Referer", "http://music.163.com/");
    request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");

    QNetworkReply *reply = networkManager->get(request);

    QTimer *timer = new QTimer(this);
    timer->setSingleShot(true);
    connect(timer, &QTimer::timeout, [reply]() {
        if(reply->isRunning()) reply->abort();
    });
    timer->start(5000);
    replyTimeouts.insert(reply, timer);

    connect(reply, &QNetworkReply::finished, [this, reply]() {
        if(replyTimeouts.contains(reply)) {
            replyTimeouts[reply]->deleteLater();
            replyTimeouts.remove(reply);
        }
        handleLyricReply(reply);
    });

    ui->lyricLabel->setText("歌词加载中...");
    ui->lyricLabel->setStyleSheet(R"(
        QLabel#lyricLabel {
            color: #FFFFFF;
            font-size: 16px;
            font-weight: bold;
            background: rgba(224, 255, 255, 0.2);
            border-radius: 10px;
            padding: 15px;
            min-height: 60px;
            qproperty-alignment: AlignCenter;
        }
    )");
}

// 获取歌手歌曲列表
void Widget_funcE_Control_industrial::fetchArtistSongs(const QString &artistId)
{
    QString url = QString("http://music.163.com/api/artist/%1").arg(artistId);

    QNetworkRequest request;
    request.setUrl(QUrl(url));
    request.setRawHeader("Referer", "http://music.163.com/");
    request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");

    QNetworkReply *reply = networkManager->get(request);

    QTimer *timer = new QTimer(this);
    timer->setSingleShot(true);
    connect(timer, &QTimer::timeout, [reply]() {
        if(reply->isRunning()) reply->abort();
    });
    timer->start(10000);
    replyTimeouts.insert(reply, timer);

    connect(reply, &QNetworkReply::finished, [this, reply]() {
        if(replyTimeouts.contains(reply)) {
            replyTimeouts[reply]->deleteLater();
            replyTimeouts.remove(reply);
        }
        handleArtistSongsReply(reply);
    });
}

// 显示当前歌词
void Widget_funcE_Control_industrial::displayCurrentLyric(qint64 currentPosition)
{
    // 缓冲状态优先显示
    if (player->bufferStatus() < 100 && player->state() == QMediaPlayer::PlayingState) {
        return;
    }

    // 无歌词处理
    if (lyricMap.isEmpty()) {
        ui->lyricLabel->setText("暂无歌词");
        ui->lyricLabel->setStyleSheet(R"(
            QLabel#lyricLabel {
                color: #AAAAAA;
                font-size: 16px;
                font-weight: normal;
                background: rgba(224, 255, 255, 0.2);
                border-radius: 10px;
                padding: 15px;
                min-height: 60px;
                qproperty-alignment: AlignCenter;
            }
        )");
        return;
    }

    // 查找当前歌词
    auto lyricIt = lyricMap.lowerBound(currentPosition);

    // 处理末尾情况
    if (lyricIt == lyricMap.end()) {
        --lyricIt;
    }
    // 处理中间情况（取前一句）
    else if (lyricIt != lyricMap.begin()) {
        auto prevIt = lyricIt;
        --prevIt;
        if (lyricIt.key() - currentPosition > 1000) {
            lyricIt = prevIt;
        }
    }

    // 显示歌词并设置样式
    ui->lyricLabel->setText(lyricIt.value());
    ui->lyricLabel->setStyleSheet(R"(
        QLabel#lyricLabel {
            color: #FF5722;
            font-size: 18px;
            font-weight: bold;
            background: rgba(224, 255, 255, 0.3);
            border-radius: 10px;
            padding: 15px;
            min-height: 60px;
            qproperty-alignment: AlignCenter;
            border: 1px solid rgba(255, 255, 255, 0.5);
        }
    )");
}

// 处理搜索结果
void Widget_funcE_Control_industrial::handleSearchReply(QNetworkReply *reply)
{
    ui->searchButton->setEnabled(true);
    ui->searchButton->setText("搜索");

    if(reply->error() != QNetworkReply::NoError) {
        QMessageBox::warning(this, "错误", "搜索失败: " + reply->errorString());
        reply->deleteLater();
        return;
    }

    QByteArray data = reply->readAll();
    QJsonDocument doc = QJsonDocument::fromJson(data);
    QJsonObject obj = doc.object();

    ui->songList->clear();
    searchResults.clear();

    int searchType = ui->searchTypeCombo->currentIndex();
    if(searchType == 0) {
        QJsonArray songs = obj.value("result").toObject().value("songs").toArray();
        for(const QJsonValue &value : songs) {
            QJsonObject song = value.toObject();
            QString name = song.value("name").toString();
            QString id = QString::number(song.value("id").toInt());

            QJsonArray artists = song.value("artists").toArray();
            QStringList artistNames;
            for(const QJsonValue &artistValue : artists) {
                artistNames << artistValue.toObject().value("name").toString();
            }

            QListWidgetItem *item = new QListWidgetItem(QString("%1 - %2").arg(name).arg(artistNames.join("/")));
            item->setData(Qt::UserRole, id);
            ui->songList->addItem(item);

            searchResults.append(qMakePair(name, id));
        }
    } else {
        QJsonArray artists = obj.value("result").toObject().value("artists").toArray();
        for(const QJsonValue &value : artists) {
            QJsonObject artist = value.toObject();
            QString name = artist.value("name").toString();
            QString id = QString::number(artist.value("id").toInt());

            QListWidgetItem *item = new QListWidgetItem(name);
            item->setData(Qt::UserRole, id);
            item->setData(Qt::UserRole+1, "artist");
            ui->songList->addItem(item);
        }
    }

    if(ui->songList->count() == 0) {
        QListWidgetItem *item = new QListWidgetItem("未找到结果");
        item->setTextAlignment(Qt::AlignCenter);
        ui->songList->addItem(item);
    }

    reply->deleteLater();
}

// 处理歌词回复
void Widget_funcE_Control_industrial::handleLyricReply(QNetworkReply *reply)
{
    if(reply->error() != QNetworkReply::NoError) {
        ui->lyricLabel->setText("歌词加载失败: " + reply->errorString());
        ui->lyricLabel->setStyleSheet(R"(
            QLabel#lyricLabel {
                color: #FF4444;
                font-size: 16px;
                font-weight: bold;
                background: rgba(224, 255, 255, 0.2);
                border-radius: 10px;
                padding: 15px;
                min-height: 60px;
                qproperty-alignment: AlignCenter;
            }
        )");
        reply->deleteLater();
        return;
    }

    QByteArray data = reply->readAll();
    QJsonDocument doc = QJsonDocument::fromJson(data);

    if(doc.isNull()) {
        ui->lyricLabel->setText("歌词解析失败（格式错误）");
        ui->lyricLabel->setStyleSheet(R"(
            QLabel#lyricLabel {
                color: #FF4444;
                font-size: 16px;
                font-weight: bold;
                background: rgba(224, 255, 255, 0.2);
                border-radius: 10px;
                padding: 15px;
                min-height: 60px;
                qproperty-alignment: AlignCenter;
            }
        )");
        reply->deleteLater();
        return;
    }

    QJsonObject obj = doc.object();
    if(!obj.contains("lrc") || obj["lrc"].toObject()["lyric"].toString().isEmpty()) {
        ui->lyricLabel->setText("暂无歌词");
        ui->lyricLabel->setStyleSheet(R"(
            QLabel#lyricLabel {
                color: #AAAAAA;
                font-size: 16px;
                font-weight: normal;
                background: rgba(224, 255, 255, 0.2);
                border-radius: 10px;
                padding: 15px;
                min-height: 60px;
                qproperty-alignment: AlignCenter;
            }
        )");
        reply->deleteLater();
        return;
    }

    QString lyricText = obj["lrc"].toObject()["lyric"].toString();
    parseLyric(lyricText);
    if (!lyricMap.isEmpty()) {
        auto firstLyric = lyricMap.begin();
        ui->lyricLabel->setText(firstLyric.value());
        ui->lyricLabel->setStyleSheet(R"(
            QLabel#lyricLabel {
                color: #FF5722;
                font-size: 18px;
                font-weight: bold;
                background: rgba(224, 255, 255, 0.3);
                border-radius: 10px;
                padding: 15px;
                min-height: 60px;
                qproperty-alignment: AlignCenter;
                border: 1px solid rgba(255, 255, 255, 0.5);
            }
        )");
    } else {
        ui->lyricLabel->setText("暂无歌词");
    }

    reply->deleteLater();
}

// 处理歌手歌曲回复
void Widget_funcE_Control_industrial::handleArtistSongsReply(QNetworkReply *reply)
{
    if(reply->error() != QNetworkReply::NoError) {
        QMessageBox::warning(this, "错误", "获取歌手歌曲失败: " + reply->errorString());
        reply->deleteLater();
        return;
    }

    QByteArray data = reply->readAll();
    QJsonDocument doc = QJsonDocument::fromJson(data);
    QJsonObject obj = doc.object();
    QJsonArray hotSongs = obj.value("hotSongs").toArray();

    ui->songList->clear();
    searchResults.clear();

    for(const QJsonValue &value : hotSongs) {
        QJsonObject song = value.toObject();
        QString name = song.value("name").toString();
        QString id = QString::number(song.value("id").toInt());

        QJsonArray artists = song.value("ar").toArray();
        QStringList artistNames;
        for(const QJsonValue &artistValue : artists) {
            artistNames << artistValue.toObject().value("name").toString();
        }

        QListWidgetItem *item = new QListWidgetItem(QString("%1 - %2").arg(name).arg(artistNames.join("/")));
        item->setData(Qt::UserRole, id);
        ui->songList->addItem(item);

        searchResults.append(qMakePair(name, id));
    }

    reply->deleteLater();
}

// 解析歌词
void Widget_funcE_Control_industrial::parseLyric(const QString &lyricText) {
    lyricMap.clear();
    if (lyricText.isEmpty()) return;

    QRegExp rx("\\[(\\d+):(\\d+)([.:])(\\d{2,3})\\]");
    QStringList lines = lyricText.split('\n');

    for (const QString &line : lines) {
        if (line.startsWith("[ti:") || line.startsWith("[ar:") || line.startsWith("[al:") ||
            line.startsWith("[by:") || line.startsWith("[offset:")) {
            continue;
        }

        int pos = 0;
        while ((pos = rx.indexIn(line, pos)) != -1) {
            int min = rx.cap(1).toInt();
            int sec = rx.cap(2).toInt();
            QString sep = rx.cap(3);
            QString msecStr = rx.cap(4);

            qint64 msec = 0;
            if (sep == ".") {
                msec = msecStr.leftJustified(3, '0').toInt();
            } else if (sep == ":") {
                msec = msecStr.toInt();
            }

            qint64 totalTime = min * 60000 + sec * 1000 + msec;
            QString lyricContent = line.mid(pos + rx.matchedLength()).trimmed();

            if (!lyricContent.isEmpty()) {
                lyricMap.insert(totalTime, lyricContent);
            }
            pos += rx.matchedLength();
        }
    }
}
